// PracticeController.java
package com.example.gymlearning.controller;

import com.example.gymlearning.entity.QuizQuestion;
import com.example.gymlearning.service.LearningContentService;
import com.example.gymlearning.service.QuizQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/practice")
@Slf4j
public class PracticeController {

    @Resource
    private LearningContentService learningContentService;

    @Resource
    private QuizQuestionService quizQuestionService;

    /**
     * 练习模式选择页面
     */
    @GetMapping("/choice")
    public String practiceChoice(@RequestParam Long pointId, Model model) {
        log.info("进入练习模式选择页面，知识点ID: {}", pointId);
        model.addAttribute("pointId", pointId);
        return "gateway-prepare";
    }

    /**
     * 练习模式准备页面
     */
    @GetMapping("/gateway/prepare-practice")
    public String practiceGatewayPrepare(@RequestParam Long pointId,
                                         @RequestParam(defaultValue = "false") boolean isPractice,
                                         Model model) {
        log.info("练习准备页面，知识点ID: {}, 模式: {}", pointId, isPractice ? "练习" : "闯关");

        model.addAttribute("pointId", pointId);
        model.addAttribute("isPractice", isPractice);

        return "gateway-prepare";
    }

    /**
     * 开始练习或闯关
     */
    @GetMapping("/gateway/start")
    public String startPracticeGateway(@RequestParam Long pointId,
                                       @RequestParam(defaultValue = "false") boolean isPractice,
                                       Model model) {
        log.info("开始{}，知识点ID: {}", isPractice ? "练习" : "闯关", pointId);

        try {
            // 创建会话
            Long sessionId = isPractice ?
                    quizQuestionService.createPracticeSession(pointId) :
                    quizQuestionService.createFormalSession(pointId);

            // 获取题目
            List<QuizQuestion> questions = isPractice ?
                    learningContentService.getPracticeQuizQuestions(pointId) :
                    learningContentService.getPracticeQuizQuestions(pointId); // 正式闯关也可以用同一套题目

            model.addAttribute("sessionId", sessionId);
            model.addAttribute("questions", questions);
            model.addAttribute("pointId", pointId);
            model.addAttribute("isPractice", isPractice);

            log.info("成功创建{}会话，题目数量: {}", isPractice ? "练习" : "闯关", questions.size());

            return "gateway-session";

        } catch (Exception e) {
            log.error("开始{}失败，pointId: {}", isPractice ? "练习" : "闯关", pointId, e);
            model.addAttribute("error", "启动失败: " + e.getMessage());
            return "redirect:/practice/gateway/prepare?pointId=" + pointId + "&isPractice=" + isPractice;
        }
    }

    /**
     * 获取练习题目API
     */
    @GetMapping("/questions")
    @ResponseBody
    public Map<String, Object> getPracticeQuestions(@RequestParam Long pointId,
                                                    @RequestParam(defaultValue = "false") boolean isPractice) {
        Map<String, Object> result = new HashMap<>();

        try {
            List<QuizQuestion> questions = learningContentService.getPracticeQuizQuestions(pointId);
            result.put("success", true);
            result.put("questions", questions);
            result.put("count", questions.size());

            log.info("获取{}题目成功，知识点ID: {}, 题目数量: {}",
                    isPractice ? "练习" : "闯关", pointId, questions.size());

        } catch (Exception e) {
            log.error("获取题目失败，pointId: {}", pointId, e);
            result.put("success", false);
            result.put("message", "获取题目失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 提交练习答案
     */
    @PostMapping("/gateway/submit")
    @ResponseBody
    public Map<String, Object> submitPractice(@RequestParam Long sessionId,
                                              @RequestParam Long pointId,
                                              @RequestParam Integer score,
                                              @RequestParam Integer totalQuestions,
                                              @RequestParam Integer correctAnswers,
                                              @RequestParam(defaultValue = "false") boolean isPractice) {
        Map<String, Object> result = new HashMap<>();

        try {
            if (isPractice) {
                // 练习模式
                quizQuestionService.completeSession(sessionId);
                result.put("isPassed", true);
                result.put("message", "练习完成！");
            } else {
                // 正式闯关模式
                boolean isPassed = quizQuestionService.completeFormalSession(
                        sessionId, score, correctAnswers, totalQuestions);
                result.put("isPassed", isPassed);
                result.put("message", isPassed ? "闯关成功！" : "闯关失败，请继续努力！");
            }

            result.put("success", true);
            result.put("score", score);
            result.put("correctAnswers", correctAnswers);
            result.put("totalQuestions", totalQuestions);

            log.info("{}提交成功，sessionId: {}, 得分: {}/{}",
                    isPractice ? "练习" : "闯关", sessionId, score, totalQuestions);

        } catch (Exception e) {
            log.error("提交{}失败，sessionId: {}", isPractice ? "练习" : "闯关", sessionId, e);
            result.put("success", false);
            result.put("message", "提交失败: " + e.getMessage());
        }

        return result;
    }
}